package com.xatz.scanner

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.xatz.ksoap2_android.SoapEnvelope
import com.xatz.ksoap2_android.serialization.SoapObject
import com.xatz.ksoap2_android.serialization.SoapSerializationEnvelope
import com.xatz.ksoap2_android.transport.HttpTransportSE
import com.xatz.scanner.bean.CarInfoBean
import com.xatz.scanner.databinding.ActivityArrivalConfirmationBinding
import com.xatz.scanner.databinding.ItemCarNumberInfoBinding
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlPullParserFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.io.IOException
import java.io.StringReader

/**
 * Created by tdq on 2022/1/4.
 */
class ArrivalConfirmationActivity : AppCompatActivity(), CarNumberInfoAdapter.OnItemClickListener {

    private var mBinding: ActivityArrivalConfirmationBinding? = null

    private val mCarInfoBeans = mutableListOf<CarInfoBean>()

    private var searchText = ""

    private val adapter = CarNumberInfoAdapter(mCarInfoBeans)

    private var kumenAdapter: ArrayAdapter<String>? = null

    private val netProgressDialog by lazy { NetProgressDialog(this) }

    private var searchContent = ""

    private var kumenContent = ""

    private val arrayList = mutableListOf<String>()

    private val mService by lazy {
        ScannerRetrofitClient().getService(
            ScannerService::class.java,
            ScannerService.baseUrl
        )
    }

    private val activityLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {

            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityArrivalConfirmationBinding.inflate(layoutInflater)
        setContentView(mBinding?.root)
        initData()
        mBinding?.srlCarNumber?.setOnRefreshListener {
            mCarInfoBeans.clear()
            initData()
        }

        mBinding?.spCarNum?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                searchText = resources.getStringArray(R.array.car_search)[p2]
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {
            }
        }

        mBinding?.btnSearch?.setOnClickListener {
            searchContent = mBinding?.etSearch?.text.toString()
            initData()
        }

        mBinding?.rvCarInfo?.adapter = adapter

        kumenAdapter =
            ArrayAdapter(this, R.layout.spinner_select_car_number, R.id.tvCarNum, arrayList)
        mBinding?.spCarNumTwo?.run {
            adapter = kumenAdapter
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    kumenContent = if(arrayList[position] == "请选择库门"){
                        ""
                    }else{
                        arrayList[position]
                    }
                    if(kumenContent.isNotBlank()){
                        initData()
                    }

                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                }
            }
            dropDownVerticalOffset = 100
        }
    }

    private fun initData() {
        Thread { getCarInfoOnNet() }.start()
        netProgressDialog.showDialog()
        when {
            searchText.isBlank() -> {
                mService.getZhuangCheList("", "", "", "", kumenContent)
                    .enqueue(object : Callback<String> {
                        override fun onResponse(call: Call<String>, response: Response<String>) {
                            if (response.isSuccessful) {
                                response.body()?.let { parseCarInfoXMLWithPull(it) }
                                adapter.setOnItemClickListener(this@ArrivalConfirmationActivity)
                                adapter.notifyDataSetChanged()
                            }
                            mBinding?.srlCarNumber?.isRefreshing = false
                            netProgressDialog.dismiss()
                        }

                        override fun onFailure(call: Call<String>, t: Throwable) {
                            Timber.e(t)
                            mBinding?.srlCarNumber?.isRefreshing = false
                            netProgressDialog.dismiss()
                        }

                    })
            }
            searchText == "钢种" -> {
                mService.getZhuangCheList(searchContent, "", "", "", kumenContent)
                    .enqueue(object : Callback<String> {
                        override fun onResponse(call: Call<String>, response: Response<String>) {
                            if (response.isSuccessful) {
                                response.body()?.let { parseCarInfoXMLWithPull(it) }
                                adapter.notifyDataSetChanged()
                            }
                            mBinding?.srlCarNumber?.isRefreshing = false
                            netProgressDialog.dismiss()
                        }

                        override fun onFailure(call: Call<String>, t: Throwable) {
                            Timber.e(t)
                            mBinding?.srlCarNumber?.isRefreshing = false
                            netProgressDialog.dismiss()
                        }

                    })
            }
            searchText == "规格" -> {
                mService.getZhuangCheList("", searchContent, "", "", kumenContent)
                    .enqueue(object : Callback<String> {
                        override fun onResponse(call: Call<String>, response: Response<String>) {
                            if (response.isSuccessful) {
                                response.body()?.let { parseCarInfoXMLWithPull(it) }
                                adapter.notifyDataSetChanged()
                            }
                            mBinding?.srlCarNumber?.isRefreshing = false
                            netProgressDialog.dismiss()
                        }

                        override fun onFailure(call: Call<String>, t: Throwable) {
                            Timber.e(t)
                            mBinding?.srlCarNumber?.isRefreshing = false
                            netProgressDialog.dismiss()
                        }

                    })
            }
            searchText == "定尺" -> {
                mService.getZhuangCheList("", "", searchContent, "", kumenContent)
                    .enqueue(object : Callback<String> {
                        override fun onResponse(call: Call<String>, response: Response<String>) {
                            if (response.isSuccessful) {
                                response.body()?.let { parseCarInfoXMLWithPull(it) }
                                adapter.notifyDataSetChanged()
                            }
                            mBinding?.srlCarNumber?.isRefreshing = false
                            netProgressDialog.dismiss()
                        }

                        override fun onFailure(call: Call<String>, t: Throwable) {
                            Timber.e(t)
                            mBinding?.srlCarNumber?.isRefreshing = false
                            netProgressDialog.dismiss()
                        }

                    })
            }
            searchText == "支数" -> {
                mService.getZhuangCheList("", "", "", searchContent, kumenContent)
                    .enqueue(object : Callback<String> {
                        override fun onResponse(call: Call<String>, response: Response<String>) {
                            if (response.isSuccessful) {
                                response.body()?.let { parseCarInfoXMLWithPull(it) }
                                val adapter = CarNumberInfoAdapter(mCarInfoBeans)
                                adapter.setOnItemClickListener(this@ArrivalConfirmationActivity)
                                mBinding?.rvCarInfo?.adapter = adapter
                            }
                            mBinding?.srlCarNumber?.isRefreshing = false
                            netProgressDialog.dismiss()
                        }

                        override fun onFailure(call: Call<String>, t: Throwable) {
                            Timber.e(t)
                            mBinding?.srlCarNumber?.isRefreshing = false
                            netProgressDialog.dismiss()
                        }

                    })
            }
        }
    }

    private fun getCarInfoOnNet() {
        arrayList.clear()
        arrayList.add("请选择库门")
        val namespace = "http://tempuri.org/"
        val transUrl = "http://www.sxjbjt.com:9084/Service1.asmx"
        val method = "GetKufangMenhao"
        //注意版本使用，这个需要跟后台询问或者从wsdl文档或者服务说明中查看
        val envolopeVersion = SoapEnvelope.VER11
        //可能是namspace+method拼接
        val soapAction = "http://tempuri.org/GetKufangMenhao"
        val request = SoapObject(namespace, method)
        //参数一定注意要有序，尽管是addProperty（），不要当作HttpUrl可以使用LinkedHashMap封装
        // SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        val envelope = SoapSerializationEnvelope(envolopeVersion)
        envelope.setOutputSoapObject(request)
        envelope.dotNet = true
        val se = HttpTransportSE(transUrl)
        try {
            se.call(soapAction, envelope) //envolopeVersion为ver12第一个参数可以为空，必须接口支持ver12才行
            val response = envelope.bodyIn as SoapObject
            //response的处理需要根据返回的具体情况，基本都要进行下面一步
            val responseSoapObject = response.getProperty("GetKufangMenhaoResult") as SoapObject
            val diffgram = responseSoapObject.getProperty("diffgram") as SoapObject
            val newDataSet = diffgram.getProperty("NewDataSet") as SoapObject
//            val Table = NewDataSet.getProperty("Table") as SoapObject
//            val KUFANGMENHAO = Table.getProperty("KUFANGMENHAO")
//            Timber.e(NewDataSet.propertyCount.toString())
            for (i in 0 until newDataSet.propertyCount) {
                val data = newDataSet.getProperty(i) as SoapObject
                try {
                    val KUFANGMENHAO = data.getProperty("KUFANGMENHAO")
                    arrayList.add(KUFANGMENHAO.toString())
                } catch (e: Exception) {
                    continue
                }
            }
            runOnUiThread {
                kumenAdapter?.notifyDataSetChanged()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: XmlPullParserException) {
            e.printStackTrace()
        }
    }

    private fun parseCarInfoXMLWithPull(xmlData: String) {
        mCarInfoBeans.clear()
        var carInfoBean: CarInfoBean? = null
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                    }
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "Table" -> {
                                carInfoBean = CarInfoBean("", "")
                            }
                            "C_DELIVERY" -> carInfoBean?.C_DELIVERY = xmlPullParser.nextText()
                            "C_PLATE_NUMBER" -> carInfoBean?.C_PLATE_NUMBER =
                                xmlPullParser.nextText()
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        if ("Table" == xmlPullParser.name) {
                            carInfoBean?.let { mCarInfoBeans.add(it) }
                            carInfoBean = null
                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Timber.e(e)
        }

    }

    override fun onItemClick(position: Int) {
        Timber.e(position.toString())
        activityLauncher.launch(
            Intent(
                this,
                ArrivalConfirmationDetailsActivity::class.java
            ).putExtra("CarInfoBean", mCarInfoBeans[position])
        )
    }
}


class CarNumberInfoAdapter(val mCarInfoBeans: MutableList<CarInfoBean>) :
    RecyclerView.Adapter<CarNumberInfoAdapter.CarNumberViewHolder>() {

    class CarNumberViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvCarNum: TextView? = null
        var tvPosition: TextView? = null

        init {
            tvCarNum = itemView.findViewById(R.id.tvCarNum)
            tvPosition = itemView.findViewById(R.id.tvPosition)
        }
    }

    private var onItemClickListener: OnItemClickListener? = null

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarNumberViewHolder {
        return CarNumberViewHolder(
            ItemCarNumberInfoBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            ).root
        )
    }

    override fun onBindViewHolder(holder: CarNumberViewHolder, position: Int) {
        holder.tvCarNum?.text = mCarInfoBeans[position].C_PLATE_NUMBER
        holder.tvPosition?.text = (position + 1).toString()
        holder.tvCarNum?.setOnClickListener {
            onItemClickListener?.onItemClick(position)
        }
    }

    override fun getItemCount(): Int {
        return mCarInfoBeans.size
    }
}